//
//  TreeLookupController.m
//  MClient
//
//  Created by  wangfei on 10-4-14.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TreeLookupController.h"
#import "MServerDAO.h"

@interface TreeLookupController (Private)
- (Boolean) isMultiSelect;
- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel;
- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel;
- (void)removeChildTreeNodes:(NSString *)positionId;
@end

@implementation TreeLookupController

@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize layoutId;
@synthesize treeData;
@synthesize treeNodes;
@synthesize treeNodePosition;
@synthesize queryFilter;
@synthesize fieldName;
@synthesize datas;
@synthesize isRoot;


#pragma mark ---- Controller加载方法 ----
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	
	if ([self isMultiSelect]) {
		[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
		[self initMultiItems:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	else {
		[self initSingleItem:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter06.html";
	self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableview.backgroundColor = [UIColor clearColor];
}


- (void)dealloc {
	[layoutId release];
	[treeData release];
	[treeNodes release];
	[treeNodePosition release];
	[fieldData release];
	[valueField release];
	[field release];	
	[labelBufferArray release];
	[valueBufferArray release];
	[queryFilter release];
	[fieldName release];
	[datas release];
    [super dealloc];
}

#pragma mark -----绘制UITableView,以及UITableView事件-----
//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [treeNodes count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 32;
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	static NSString *menuCellIdentifier = @"TreeLookupCellIdentifier";
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:menuCellIdentifier] autorelease];
	cell.backgroundColor = [UIColor clearColor];
	cell.accessoryType = UITableViewCellAccessoryNone;
	cell.selectionStyle = UITableViewCellSelectionStyleBlue;//选中行的颜色
	
	NSMutableDictionary *treeNode = [self.treeNodes objectAtIndex:row];
	int stage = 0;
	UIButton *button = [[UIButton alloc] init];
	if ([treeNode objectForKey:@"hc"]) {
		bool hasChild = [[treeNode objectForKey:@"hc"]boolValue];
		if (hasChild || [treeNode objectForKey:@"ns"]) {
			if ([[treeNode objectForKey:@"expanded"] isEqualToString:@"0"]) {
				[button setBackgroundImage:[UIImage imageNamed:@"tree_plus.png"] forState:UIControlStateNormal];
			}else {
				[button setBackgroundImage:[UIImage imageNamed:@"tree_minus.png"] forState:UIControlStateNormal];
			}
		}else {
			[button setBackgroundImage:[UIImage imageNamed:@"tree_nochild.png"] forState:UIControlStateNormal];
		}
	}
	
	if ([treeNode objectForKey:@"stage"]) {
		stage = [[treeNode objectForKey:@"stage"] intValue];
	}
	button.frame = CGRectMake(6.0f + (stage * 20), 4.0f, 24, 24);
	button.tag = row;
	[button addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
	[cell addSubview:button];
	
	[button release];
	
	UIButton *folder = [[UIButton alloc] init];
	if ([treeNode objectForKey:@"hc"]) {
		bool hasChild = [[treeNode objectForKey:@"hc"]boolValue];
		if (hasChild || [treeNode objectForKey:@"ns"]) {
			if ([[treeNode objectForKey:@"expanded"] isEqualToString:@"0"]) {
				[folder setBackgroundImage:[UIImage imageNamed:@"folder_close.png"] forState:UIControlStateNormal];
			}else {
				[folder setBackgroundImage:[UIImage imageNamed:@"folder_open.png"] forState:UIControlStateNormal];
			}
		}else {
			[folder setBackgroundImage:[UIImage imageNamed:@"tree_nochild.png"] forState:UIControlStateNormal];
		}
	}
	folder.frame = CGRectMake(30.0f + (stage * 20), 1.0f, 30, 30);
	folder.tag = row;
	[folder addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
	[cell addSubview:folder];
	[folder release];	
	
	
	CGRect tRect1 = CGRectMake(65.0f + (stage * 20), 0.0f, 280.0f, 32.0f);
	id treeLabel = [[UILabel alloc] initWithFrame:tRect1];
	NSString *label = [treeNode objectForKey:@"lbl"];
	((UILabel*)treeLabel).backgroundColor = [UIColor clearColor];
	[treeLabel setText:label];
	[treeLabel setTextAlignment:UITextAlignmentLeft];
	[treeLabel setFont:[UIFont fontWithName:@"Georgia" size:18.0f]];
	[treeLabel setNumberOfLines:1];
	[cell addSubview:treeLabel];
	[treeLabel release];
	
	for (int i = 0; i < [valueBufferArray count]; i++) {
		if ([[treeNode objectForKey:@"id"] isEqualToString:[valueBufferArray objectAtIndex:i]]){
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			break;
		}
	}
	return cell;
}


#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	isRoot = YES;
	[[MServerDAO sharedInstance] getTreeAsync:self.layoutId
								  queryFilter:queryFilter
									 delegate:self];
}

-(void)doAction:(id)inSender {
	@try{
		UIButton *b = (UIButton *)inSender;
		int row = b.tag;	
		if (treeNodePosition) {
			[treeNodePosition release];
			treeNodePosition = nil;
		}
		self.treeNodePosition = [self.treeNodes objectAtIndex:row];
		int stage = [[treeNodePosition objectForKey:@"stage"]intValue];
		int position = [[treeNodePosition objectForKey:@"position"]intValue];
		
		if ([treeNodePosition objectForKey:@"ns"]) {
			if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"1"]){
				[self removeChildTreeNodes:[treeNodePosition objectForKey:@"id"]];
				[treeNodePosition setObject:@"0" forKey:@"expanded"];
				for(int i = 0; i< [self.treeNodes count]; i++){
					NSMutableDictionary *tempTreeNode = [self.treeNodes objectAtIndex:i];
					[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
				}
				[self.tableview reloadData];
				return;
			}
		}
		if (![treeNodePosition objectForKey:@"ns"]) {
			if([treeNodePosition objectForKey:@"hc"]){
				bool hasChild = [[treeNodePosition objectForKey:@"hc"]boolValue];
				if(hasChild){
					isRoot = NO;
					[[MServerDAO sharedInstance] getNodeAsync:[treeNodePosition objectForKey:@"nid"] == nil?@"":[treeNodePosition objectForKey:@"nid"]
													   treeId:[treeNodePosition objectForKey:@"id"] == nil?@"":[treeNodePosition objectForKey:@"id"] 
												  queryFilter:[treeNodePosition objectForKey:@"ft"] == nil?[NSMutableArray array]:[treeNodePosition objectForKey:@"ft"]
														param:[treeNodePosition objectForKey:@"param"] == nil?[NSMutableDictionary dictionary]:[treeNodePosition objectForKey:@"param"]
													 delegate:self];
					
				}
				
			}
		}else {
			if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"0"]){
				NSMutableArray *childTreeNodes = [treeNodePosition objectForKey:@"ns"];
				
				for(int j = 0; j < [childTreeNodes count]; j++ ){
					[[childTreeNodes objectAtIndex:j] setObject:[NSNumber numberWithInteger:stage + 1] forKey:@"stage"];
					[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"index"] forKey:@"index"];
					[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"id"] forKey:@"fatherId"];
					[[childTreeNodes objectAtIndex:j] setObject:@"0" forKey:@"expanded"];
				}
				int currentIndex = position + 1;
				for (int i = 0; i<[childTreeNodes count]; i++) {
					[treeNodes insertObject:[childTreeNodes objectAtIndex:i] atIndex:currentIndex];
					currentIndex++;
				}
				[treeNodePosition setObject:@"1" forKey:@"expanded"];
				for(int i = 0; i< [treeNodes count]; i++){
					NSMutableDictionary *tempTreeNode = [treeNodes objectAtIndex:i];
					[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
				}
				
				[self.tableview reloadData];
				return;
			}
		}	
	}@catch (NSException *e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}	
}


#pragma mark -----与服务器异步同步回调方法-----
- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if (isRoot) {
		self.treeData = returnValue;
		
		self.title = [treeData objectForKey:@"lbl"];
		
		self.treeNodes = [treeData objectForKey:@"ns"];
		
		if (treeNodes == nil) {
			treeNodes = [[NSMutableArray alloc]init];
		}
		
		for (int i = 0; i < [treeNodes count]; i++) {
			NSMutableDictionary *treeNode = [treeNodes objectAtIndex:i];
			[treeNode setObject:@"0" forKey:@"expanded"];
			[treeNode setObject:[NSNumber numberWithInteger:0] forKey:@"stage"];
			[treeNode setObject:[NSNumber numberWithInteger:i] forKey:@"index"];
			[treeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
		}
		[self.tableview reloadData];
	}else {
		NSMutableDictionary *treeChildData = [returnValue retain];
		int stage = [[treeNodePosition objectForKey:@"stage"]intValue];
		int position = [[treeNodePosition objectForKey:@"position"]intValue];
		
		NSMutableArray *treeChildNodes = [treeChildData objectForKey:@"ns"] == nil?[NSMutableArray array]:[treeChildData objectForKey:@"ns"];
		[treeNodePosition setObject:treeChildNodes forKey:@"ns"];
		if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"0"]){
			NSMutableArray *childTreeNodes = [treeNodePosition objectForKey:@"ns"]; 
			for(int j = 0; j < [childTreeNodes count]; j++ ){
				[[childTreeNodes objectAtIndex:j] setObject:[NSNumber numberWithInteger:stage + 1] forKey:@"stage"];
				[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"index"] forKey:@"index"];
				[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"id"] forKey:@"fatherId"];
				[[childTreeNodes objectAtIndex:j] setObject:@"0" forKey:@"expanded"];
			}
			int currentIndex = position + 1;
			for (int i = 0; i<[childTreeNodes count]; i++) {
				[treeNodes insertObject:[childTreeNodes objectAtIndex:i] atIndex:currentIndex];
				currentIndex++;
			}
			[treeNodePosition setObject:@"1" forKey:@"expanded"];
			for(int i = 0; i< [treeNodes count]; i++){
				NSMutableDictionary *tempTreeNode = [treeNodes objectAtIndex:i];
				[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
			}
			
			[self.tableview reloadData];
			return;
		}
	}
}

//选中一个cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	int row = [indexPath row];
	
	NSMutableDictionary *treeNode = [treeNodes objectAtIndex:row];
	
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	
	if ([self isMultiSelect]) {
		if ([[treeNode objectForKey:@"es"]boolValue]) {
			bool selectFlag = YES;
			for (int i = 0; i < [valueBufferArray count]; i++) {
				NSString *key = [valueBufferArray objectAtIndex:i];
				if ([[treeNode objectForKey:@"id"] isEqualToString:key]) {
					[valueBufferArray removeObjectAtIndex:i];
					[labelBufferArray removeObjectAtIndex:i];
					selectFlag = NO;
					break;
				}
			}
			if (selectFlag) {
				[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
				[valueBufferArray addObject:[treeNode objectForKey:@"id"] == nil?@"":[treeNode objectForKey:@"id"]];
				[labelBufferArray addObject:[treeNode objectForKey:@"lbl"] == nil?@"":[treeNode objectForKey:@"lbl"]];
			}else {
				[cell setAccessoryType:UITableViewCellAccessoryNone];
			}	
		}else {
			UIButton *button = [[UIButton alloc] init];
			button.tag = row;
			[self doAction:button];
			[button release];
		}

	}else {
		if ([[treeNode objectForKey:@"es"]boolValue]) {
			if ([valueBufferArray count] > 0) {
				[valueBufferArray removeObjectAtIndex:0];
			}
			if ([labelBufferArray count] > 0) {
				[labelBufferArray removeObjectAtIndex:0];
			}
			[valueBufferArray addObject:[treeNode objectForKey:@"id"] == nil?@"":[treeNode objectForKey:@"id"]];
			[labelBufferArray addObject:[treeNode objectForKey:@"lbl"] == nil?@"":[treeNode objectForKey:@"lbl"]];
			
			NSString *labelString = @"";
			NSString *valueString = @"";
			for(int i = 0; i<[ valueBufferArray count]; i++) {
				valueString = [valueString stringByAppendingFormat:@"%@,",[valueBufferArray objectAtIndex:i]];
				labelString = [labelString stringByAppendingFormat:@"%@,",[labelBufferArray objectAtIndex:i]];
			}
			if ([labelString length] > 0) {
				labelString = [labelString substringToIndex:[labelString length] - 1];
				valueString = [valueString substringToIndex:[valueString length] - 1];
			}
			[self.fieldData setObject:valueString forKey:@"value"];
			[self.fieldData setObject:labelString forKey:@"lbl"];
			self.valueField.text = labelString;
			
			[self.navigationController popViewControllerAnimated:YES];
		}else {
			UIButton *button = [[UIButton alloc] init];
			button.tag = row;
			[self doAction:button];
			[button release];
		}
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark ---- 按钮事件处理方法 ----

//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	@try {
		NSString *labelString = @"";
		NSString *valueString = @"";
		for(int i = 0;i<[valueBufferArray count]; i++) {
			valueString = [valueString stringByAppendingFormat:@"%@,",[valueBufferArray objectAtIndex:i]];
			labelString = [labelString stringByAppendingFormat:@"%@,",[labelBufferArray objectAtIndex:i]];
		}
		if ([labelString length] > 0) {
			labelString = [labelString substringToIndex:[labelString length] - 1];
			valueString = [valueString substringToIndex:[valueString length] - 1];
		}
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		[self.navigationController popViewControllerAnimated:YES];
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel {
	labelBufferArray = [[NSMutableArray alloc] init];
	valueBufferArray = [[NSMutableArray alloc] init];
	if (aValue == nil || [aValue isEqualToString:@""]) {
		return;
	}
	
	NSMutableArray *values = [[NSMutableArray alloc] initWithArray:[aValue componentsSeparatedByString:@","]];
	for(int i = 0; i < [values count];i++) {
		if (i == 0 || i == [values count] - 1) {
			if ([[values objectAtIndex:i] isEqualToString:@""]) {
				continue;
			}
		}
		[valueBufferArray addObject:[values objectAtIndex:i]];
	}
	if (aLabel != nil && ![aLabel isEqualToString:@""]) {
		NSMutableArray *labels = [[NSMutableArray alloc] initWithArray:[aLabel componentsSeparatedByString:@","]];
		for(int i = 0; i < [labels count]; i++) {
			[labelBufferArray addObject:[labels objectAtIndex:i]];
		}	
	}
	int count = [valueBufferArray count] - [labelBufferArray count];
	if (count > 0) {
		for (int i = 0; i < count; i++) {
			NSString *value = [[valueBufferArray objectAtIndex:i] copy];
			[labelBufferArray addObject:value];
		}
	}else if (count < 0) {
		for (int i = -count-1; i >= 0; i--) {
			[labelBufferArray removeObjectAtIndex:i];
		}
	}
}

- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel {
	valueBufferArray = [[NSMutableArray alloc] init];
	labelBufferArray = [[NSMutableArray alloc] init];
	if (aValue != nil && ![aValue isEqualToString:@""]) {
		[valueBufferArray addObject:aValue];
		[labelBufferArray addObject:aLabel == nil?@"":aLabel];
	}
}

- (void)removeChildTreeNodes:(NSString *)positionId {
	for(int i = 0; i < [self.treeNodes count]; i++){
		if(![[treeNodes objectAtIndex:i]objectForKey:@"fatherId"])
			continue;
		if([[[treeNodes objectAtIndex:i]objectForKey:@"fatherId"] isEqualToString:positionId]){
			NSString *fatherId = [[treeNodes objectAtIndex:i]objectForKey:@"id"];
			[treeNodes removeObjectAtIndex:i];		
			i--;
			[self removeChildTreeNodes:fatherId];
		}
	}
}

- (Boolean)isMultiSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"U"]) {
		return YES;
	}
	return NO;
}


@end
